<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col class="flex flex-wrap gap-4" :sm="24" :lg="24" style="padding-left: 20px">
        <el-row :gutter="20" style="display: flex; justify-content: flex-start">
          <el-col :sm="24" :lg="6" style="padding-left: 10px" class="item" v-for="(item, index) in labelList" :key="index">
            <div class="content p-6">
              <div class="dashboard-item-top">
                <div :style="{ fontSize: `${resizeTime * 16}px`, marginBottom: '20px' }">{{ item.label }}</div>
                <div :style="{ fontSize: `${resizeTime * 32}px` }">{{ item.count }} <span>台</span></div>
              </div>
              <div class="dashboard-item-left">
                <div class="dashboard-chart-container" id="moneyContainer">
                  <img :src="item.icon" alt="" width="80" height="80" />
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-col>
      <el-col :sm="24" :lg="24" style="padding-left: 20px; margin-top: 20px">
        <el-card shadow="hover">
          <template #header>
            <div style="display: flex; justify-content: space-between; padding-bottom: 16px">
              <div>
                <PieChart style="width: 1em; height: 1em; vertical-align: middle; margin-right: 0.5em" />
                <span :style="{ verticalAlign: 'middle', fontSize: `${resizeTime * 20}px` }">设备数量</span>
              </div>
              <div class="time" style="display: flex; justify-content: center; width: 50%">
                <el-button
                  v-for="(item, index) in timeList"
                  :key="index"
                  :type="queryParams.dateType == item.value ? 'primary' : 'default'"
                  variant="outline"
                  @click="changeTime(item.value, 'device')"
                >
                  {{ item.name }}
                </el-button>
                <div class="dashboard-chart-title-container" style="margin-left: 20px">
                  <el-date-picker
                    v-model="datetimerange"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="changeTimePicker"
                  ></el-date-picker>
                </div>
              </div>
            </div>
          </template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="deviceStats" style="height: 420px" />
          </div>
        </el-card>
      </el-col>
      <el-col :sm="24" :lg="24" style="padding-left: 20px; margin-top: 20px">
        <el-card shadow="hover">
          <template #header>
            <div style="display: flex; justify-content: space-between; padding-bottom: 16px">
              <div>
                <PieChart style="width: 1em; height: 1em; vertical-align: middle; margin-right: 0.5em" />
                <span :style="{ verticalAlign: 'middle', fontSize: `${resizeTime * 20}px` }">用户注册数据</span>
              </div>
              <div class="time" style="display: flex; justify-content: center; width: 50%">
                <el-button
                  v-for="(item, index) in timeList"
                  :key="index"
                  :type="queryParams1.dateType == item.value ? 'primary' : 'default'"
                  variant="outline"
                  @click="changeTime(item.value, 'user')"
                >
                  {{ item.name }}
                </el-button>
                <div class="dashboard-chart-title-container" style="margin-left: 20px">
                  <el-date-picker
                    v-model="datetimerange1"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="changeTimePicker1"
                  ></el-date-picker>
                </div>
              </div>
            </div>
          </template>
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="userStats" style="height: 420px" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Index" lang="ts">
import { deviceStatistics, userStatistics } from '@/api/home';
import * as echarts from 'echarts';
import { PieChart } from '@element-plus/icons-vue';
import { FormStVO, CountStQuery } from '@/api/home/types';
import { getDeviceCount } from '@/api/device/device';
import { DeviceCountVO } from '@/api/device/types';
import shebIcon from '@/assets/images/shebIcon.png';
import guzIcon from '@/assets/images/guzIcon.png';
import lixIcon from '@/assets/images/lixIcon.png';
import zaixIcon from '@/assets/images/zaixIcon.png';

const userStats = ref();
const deviceStats = ref();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const datetimerange = ref<[DateModelType, DateModelType]>(['', '']);
const datetimerange1 = ref<[DateModelType, DateModelType]>(['', '']);
const labelList = ref<DeviceCountVO[]>([]);
const resizeTime = ref(1);
const queryParams = ref<CountStQuery>({
  dateType: 2,
  startDate: null,
  endDate: null
});
const queryParams1 = ref<CountStQuery>({
  dateType: 2,
  startDate: null,
  endDate: null
});
const timeList = ref([
  {
    name: '今日',
    value: 1
  },
  {
    name: '本月',
    value: 2
  },
  {
    name: '本年',
    value: 3
  }
]);

/** 获取设备全部 在线 离线的状态的数量 */
const getAllDeviceCount = async () => {
  const res = await getDeviceCount();
  res.data[0].icon = shebIcon;
  res.data[1].icon = zaixIcon;
  res.data[2].icon = lixIcon;
  res.data[3].icon = guzIcon;
  labelList.value = res.data;
};

const getDeviceList = async () => {
  proxy?.$modal.loading('正在加载订单数据，请稍候！');
  const res = await deviceStatistics(queryParams.value);
  proxy?.$modal.closeLoading();
  let xAxisList = res.data.map((item: any) => {
    return item.label;
  });
  let totalSeries = res.data.map((item: any) => {
    return item.totalCount;
  });
  let onLineSeries = res.data.map((item: any) => {
    return item.onLineCount;
  });
  let countSeries = res.data.map((item: any) => {
    return item.offCount;
  });
  const commandstatsIntance = echarts.init(deviceStats.value, 'macarons');
  commandstatsIntance.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '离线',
        data: countSeries,
        type: 'bar',
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '在线',
        data: onLineSeries,
        type: 'bar',
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '全部',
        data: totalSeries,
        type: 'bar',
        emphasis: {
          focus: 'series'
        }
      }
    ]
  });
  window.addEventListener('resize', () => {
    commandstatsIntance.resize();
  });
};

const getUserList = async () => {
  proxy?.$modal.loading('正在加载订单数据，请稍候！');
  const res = await userStatistics(queryParams1.value);
  proxy?.$modal.closeLoading();
  let xAxisList = res.data.map((item: any) => {
    return item.label;
  });
  let orderSeries = res.data.map((item: any) => {
    return item.count;
  });
  const commandstatsIntance = echarts.init(userStats.value, 'macarons');
  commandstatsIntance.setOption({
    tooltip: {
      trigger: 'item'
    },
    xAxis: {
      type: 'category',
      data: xAxisList
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: orderSeries,
        type: 'line'
      }
    ]
  });
  window.addEventListener('resize', () => {
    commandstatsIntance.resize();
  });
};

const changeTimePicker = (e) => {
  if (e) {
    queryParams.value.startDate = `${e[0]}`;
    queryParams.value.endDate = `${e[1]}`;
    getDeviceList();
  } else {
    queryParams.value.startDate = null;
    queryParams.value.endDate = null;
    getDeviceList();
  }
};

const changeTimePicker1 = (e) => {
  if (e) {
    queryParams1.value.startDate = `${e[0]}`;
    queryParams1.value.endDate = `${e[1]}`;
    getUserList();
  } else {
    queryParams1.value.startDate = null;
    queryParams1.value.endDate = null;
    getUserList();
  }
};

const changeTime = (index: number, type: string) => {
  if (type == 'device') {
    queryParams.value.dateType = index;
    getDeviceList();
  }
  if (type == 'user') {
    queryParams1.value.dateType = index;
    getUserList();
  }
};

const updateContainer = () => {
  if (document.documentElement.clientWidth >= 1400 && document.documentElement.clientWidth < 1920) {
    resizeTime.value = Number((document.documentElement.clientWidth / 2080).toFixed(2));
  } else if (document.documentElement.clientWidth < 1080) {
    resizeTime.value = Number((document.documentElement.clientWidth / 1080).toFixed(2));
  } else {
    resizeTime.value = 1;
  }
};

onMounted(() => {
  getDeviceList();
  getUserList();
  getAllDeviceCount();
  nextTick(() => {
    updateContainer();
  });
});
const { width, height } = useWindowSize();
watch([width, height], () => {
  updateContainer();
});
</script>

<style scoped lang="scss">
.time {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .title {
    font-size: 16px;
  }
}
.content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  &:hover {
    box-shadow: 0 0 12px 0 rgba(0, 0, 0, 0.2);
  }
  .dashboard-item-top span {
    font-size: 16px;
    color: #666;
  }
}
</style>
